﻿Imports System.Data

Partial Class Content_Administracion_Adm_controls_Catalogo
    Inherits System.Web.UI.UserControl
    Dim IDataBase As New Clases.DataBase
    Dim ECConnString As String = ConfigurationManager.AppSettings("dbIP")
    Dim IControles As New Clases.controles
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then
            Dim q1, q2, q3, q4, q5, q6, q7, q8, q10 As String

            txt_inst.Text.ToUpper()
            txt_calleInst.Text.ToUpper()
            txt_coloniaInst.Text.ToUpper()
            txt_paisInst.Text.ToUpper()
            txt_edoInst.Text.ToUpper()
            txt_munInst.Text.ToUpper()

            'IControles.fill_dropDownListBaseQuery(ddl_statusPer, "TEstatus", "stat_id", "stat_nombre", q2)
            'IControles.addNoneAllElement(ddl_statusPer)
            'IControles.fill_dropDownListBaseQuery(ddl_estatus_desp, "TEstatus", "stat_id", "stat_nombre", q2)
            'IControles.addNoneAllElement(ddl_estatus_desp)

            Dim dt As New DataTable
            q3 = "select * from vwInst where stat_id=1"
            IDataBase.createDataTable(dt, q3)


            If dt.Rows.Count <= 0 Then

                Label64.Visible = True
                Label64.Text = "No hay Instituciones registradas hasta el momento"

            Else
                Label64.Visible = False
                IControles.fillGridViewPaging(gv_Instituciones, q3)
            End If

            Dim dtPer As New DataTable
            q5 = "select * from vwPerf"
            IDataBase.createDataTable(dtPer, q5)
            If dtPer.Rows.Count <= 0 Then
                Label13.Visible = True
                Label13.Text = "No hay Perfiles registrados hasta el momento"
            Else
                Label13.Visible = False
                IControles.fillGridViewPaging(gv_Perfil, q5)
            End If


            Dim dtEmi As New DataTable
            q6 = "select * from tEmisoras where stat_id =1"
            IDataBase.createDataTable(dtEmi, q6)

            If dtEmi.Rows.Count <= 0 Then
                Label14.Visible = True
                Label14.Text = "No hay Emisoras registradas hasta el momento"
            Else
                Label14.Visible = False
                IControles.fillGridViewPaging(gv_Emisoras, q6)
            End If



            Dim dtDesp As New DataTable
            q7 = "select * from vwDespachos"
            IDataBase.createDataTable(dtDesp, q7)

            If dtDesp.Rows.Count <= 0 Then
                Label15.Visible = True
                Label15.Text = "No hay despachos registrados hasta el momento"
            Else
                Label15.Visible = False
                IControles.fillGridViewPaging(gv_despachos, q7)
            End If

            LoadTipos()

            Dim iva, eiva As String
            iva = "Select iva_valor from Tiva"
            eiva = IDataBase.getSimpleData(iva, "iva_valor")
            txtIVA.Text = Replace(eiva, ",", ".")

        End If

    End Sub

    'Inicia el ABC de Instituciones

#Region "Instituciones"

    Protected Sub btn_regInst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_regInst.Click
        Dim q1, q2, dmlinst(), resultTransaction, valInst As String
        q1 = "Select Count(*) As Instituciones  from TInstituciones where Inst_nombre='" & txt_inst.Text & "'"
        valInst = IDataBase.getSimpleData(q1, "Instituciones")

        If valInst <= 0 Then
            q2 = "insert into tinstituciones(inst_nombre,inst_calle,inst_numero,inst_colonia,inst_cp,pais_nombre,edo_nombre,mun_nombre,inst_telefono,inst_tarifa,stat_id,inst_titular) " & _
                "values ('" & txt_inst.Text & "','" & txt_calleInst.Text & "','" & txt_numeroInst.Text & "','" & txt_coloniaInst.Text & "','" & txt_CP.Text & "','" & txt_paisInst.Text.ToUpper & "','" & txt_edoInst.Text.ToUpper & "','" & txt_munInst.Text.ToUpper & "','" & txt_tel.Text & "', '" & txt_tarifa.Text & "','1','" & Session("ActiveUserlogin") & "')"
            IDataBase.addStringToArray(dmlinst, q2)

            resultTransaction = IDataBase.execute_commandsArray(dmlinst, lbl_errorInst)
            If resultTransaction = "OK" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Institución Registrada Exitosamente');", True)
            Else
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
            End If
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('La institución ya existe');", True)
        End If
        TabC1.ActiveTabIndex = 0
        clearFieldData()
        busquedaInst()
    End Sub
    Protected Sub busquedaInst()
        Dim qr As String
        Dim dt As Integer = IDataBase.getSimpleData("select Count(*)as suma from vwInst where stat_id=1", "suma")
        If dt <= 0 Then

        Else
            Label64.Visible = False
            qr = "select * from vwInst where inst_nombre like '" & txtbusquedaInst.Text & "%' and stat_id=1"
            IControles.fillGridViewPaging(gv_Instituciones, qr)

        End If
    End Sub
    Protected Sub lopa_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles lopa.Click
        busquedaInst()
    End Sub
    Protected Sub btn_modInst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_modInst.Click
        Dim dmlUpdateInst() As String
        Dim UpdateInst As String
        Dim resultTransaction As String

        UpdateInst = "Update Tinstituciones set inst_nombre='" & txt_inst.Text & "',inst_calle='" & txt_calleInst.Text & "',inst_numero= '" & txt_numeroInst.Text & "',inst_colonia= '" & txt_coloniaInst.Text & "',inst_cp='" & txt_CP.Text & "',pais_nombre='" & txt_paisInst.Text.ToUpper & "',edo_nombre='" & txt_edoInst.Text.ToUpper & "',mun_nombre='" & txt_munInst.Text.ToUpper & "'" & _
            ", inst_telefono='" & txt_tel.Text & "', inst_tarifa='" & txt_tarifa.Text & "',inst_titular='" & Session("usr_id") & "' where inst_id='" & Session("inst_id") & "' "
        IDataBase.addStringToArray(dmlUpdateInst, UpdateInst)

        resultTransaction = IDataBase.execute_commandsArray(dmlUpdateInst, lb_error)

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Institución Modificada Exitosamente');", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If

        TabC1.ActiveTabIndex = 0
        clearFieldData()
        busquedaInst()

    End Sub

    Protected Sub gv_Instituciones_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv_Instituciones.RowCommand
        If e.CommandName = "editarInst" Then
            clearFieldData()
            loadInstData(e.CommandArgument)
        ElseIf e.CommandName = "eliminaInst" Then
            clearFieldData()
            eliminaInst(e.CommandArgument)
        End If
    End Sub

    Protected Sub loadInstData(ByVal inst_ID As Integer)
        btn_regInst.Visible = False
        btn_modInst.Visible = True


        Dim dt As New DataTable
        Dim datosInst As String = "select Distinct Top 1 * from vwInst where inst_id ='" & inst_ID & "'"
        IDataBase.createDataTable(dt, datosInst)

        If dt IsNot Nothing Then
            txt_inst.Text = dt.Rows(0)("inst_nombre")
            txt_calleInst.Text = dt.Rows(0)("inst_calle")
            txt_numeroInst.Text = dt.Rows(0)("inst_numero")
            txt_coloniaInst.Text = dt.Rows(0)("inst_colonia")
            txt_CP.Text = dt.Rows(0)("inst_CP")
            txt_edoInst.Text = dt.Rows(0)("edo_nombre")

            txt_paisInst.Text = dt.Rows(0)("pais_nombre")
            txt_munInst.Text = dt.Rows(0)("mun_nombre")

            txt_tel.Text = dt.Rows(0)("inst_telefono")
            txt_tarifa.Text = Replace(dt.Rows(0)("inst_tarifa"), ",", ".")
        End If
        Session("inst_id") = inst_ID
    End Sub
    Protected Sub eliminaInst(ByVal id As Integer)
        Dim array(), query2, resultTransaction As String
        Dim valor, q As String
        q = "select COUNT(*) as cantidad from TClientes where inst_id = " & id
        valor = IDataBase.getSimpleData(q, "cantidad")
        If valor = "0" Then
            query2 = "delete from TInstituciones where inst_id = " & id
            IDataBase.addStringToArray(array, query2)
            resultTransaction = IDataBase.execute_commandsArray(array, lb_error)
        End If

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Institución eliminada Exitosamente');", True)
        Else

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Mensaje de error en eliminar Institución: No se puede dar de baja esta Institución ya que existe al menos un cliente con esta Institución');", True)
        End If

        IControles.fillGridViewPaging(gv_Instituciones, "select * from vwInst")
    End Sub
    Protected Sub btn_canInst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_canInst.Click
        clearFieldData()
    End Sub

    Protected Sub clearFieldData()
        btn_regInst.Visible = True
        btn_modInst.Visible = False

        txt_inst.Text = ""
        txt_calleInst.Text = ""
        txt_numeroInst.Text = ""
        txt_coloniaInst.Text = ""
        txt_CP.Text = ""
        txt_paisInst.Text = ""
        txt_edoInst.Text = ""
        txt_munInst.Text = ""
        txt_tel.Text = ""
        txt_tarifa.Text = ""

    End Sub



#End Region

#Region "Perfiles"
    Protected Sub loadgridPerfil()
        Dim dtPer As New DataTable
        Dim q5 As String
        q5 = "select * from vwPerf"
        IDataBase.createDataTable(dtPer, q5)
        If dtPer.Rows.Count <= 0 Then
            Label13.Visible = True
            Label13.Text = "No hay Perfiles registrados hasta el momento"
        Else
            Label13.Visible = False
            IControles.fillGridViewPaging(gv_Perfil, q5)
        End If
    End Sub
    Protected Sub btn_regPer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_regPer.Click
        Dim q1, q2, dmlPer(), resultTransaction, valPer As String
        Dim valor, valorcap As Double

        q1 = "Select Count(*) As Perfiles  from TPerfiles where per_nombre='" & txt_nombrePer.Text & "'"
        valPer = IDataBase.getSimpleData(q1, "Perfiles")

        If valPer <= 0 Then
            q2 = "insert into tperfiles(per_nombre,per_capitales,per_tipo_a,per_tipo_b," & _
                "per_tipo_c,per_notas_estruc,per_deuda,per_fondo_inv,stat_id,per_titular) values ('" & txt_nombrePer.Text & _
                "'," & txt_Cap.Text & "," & txt_A.Text & "," & txt_A0.Text & "," & txt_A1.Text & "," & txt_A2.Text & _
                "," & txt_Deuda.Text & "," & txt_Fondo_Inv.Text & ",1,'" & Session("ActiveUserlogin") & "')"
                IDataBase.addStringToArray(dmlPer, q2)
                resultTransaction = IDataBase.execute_commandsArray(dmlPer, [lb_error])
            
            If resultTransaction = "OK" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Perfil Registrado Exitosamente');", True)
            Else
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
            End If
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El perfil ya existe');", True)
            Exit Sub
        End If
        TabC1.ActiveTabIndex = 1
        clearFieldDataPerfil()
        loadgridPerfil()
    End Sub

    Protected Sub btn_modifPer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_modifPer.Click
        Dim dmlUpdatePer() As String
        Dim UpdatePer As String
        Dim resultTransaction As String

        UpdatePer = "update tperfiles set per_nombre ='" & txt_nombrePer.Text & "', per_capitales=" & txt_Cap.Text & ", per_tipo_a=" & txt_A.Text & _
                    ", per_tipo_b=" & txt_A0.Text & ", per_tipo_c=" & txt_A1.Text & ",per_notas_estruc=" & txt_A2.Text & ",per_deuda=" & txt_Deuda.Text & _
                    ", per_fondo_inv=" & txt_Fondo_Inv.Text & ",stat_id=1,per_titular='" & Session("ActiveUserLogin") & _
                    "' where per_id = " & Session("per_id")

        IDataBase.addStringToArray(dmlUpdatePer, UpdatePer)

        resultTransaction = IDataBase.execute_commandsArray(dmlUpdatePer, lb_error)

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Perfil Modificado Exitosamente');", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Mensaje de error en eliminar perfil: No se puede dar de baja este perfil ya que existe  al menos un cliente con este perfil');", True)
        End If
        TabC1.ActiveTabIndex = 1
        clearFieldDataPerfil()
        loadgridPerfil()
    End Sub

    Protected Sub loadPerData(ByVal per_ID As Integer)
        btn_regPer.Visible = False
        btn_modifPer.Visible = True

        Dim dt As New DataTable
        Dim datosPer As String = "select Distinct Top 1 * from vwPerf where per_id ='" & per_ID & "'"
        IDataBase.createDataTable(dt, datosPer)

        If dt IsNot Nothing Then
            txt_nombrePer.Text = dt.Rows(0)("per_nombre")
            txt_Cap.Text = Replace(dt.Rows(0)("per_capitales"), ",", ".")
            txt_A.Text = Replace(dt.Rows(0)("per_tipo_a"), ",", ".")
            txt_A0.Text = Replace(dt.Rows(0)("per_tipo_b"), ",", ".")
            txt_A1.Text = Replace(dt.Rows(0)("per_tipo_c"), ",", ".")
            txt_A2.Text = Replace(dt.Rows(0)("per_notas_estruc"), ",", ".")
            txt_Deuda.Text = Replace(dt.Rows(0)("per_deuda"), ",", ".")
            txt_Fondo_Inv.Text = Replace(dt.Rows(0)("per_fondo_inv"), ",", ".")
            'ddl_statusPer.SelectedValue = dt.Rows(0)("stat_id")
        End If
        Session("per_id") = per_ID
    End Sub

    Protected Sub clearFieldDataPerfil()
        btn_regPer.Visible = True
        btn_modifPer.Visible = False
        txt_nombrePer.Text = ""
        txt_Cap.Text = ""
        txt_A.Text = ""
        txt_A0.Text = ""
        txt_A1.Text = ""
        txt_A2.Text = ""
        txt_Deuda.Text = ""
        txt_Fondo_Inv.Text = ""
        'ddl_statusPer.SelectedValue = "None"
        'ddl_statusPer.SelectedValue = "None"
    End Sub

    Protected Sub gv_Perfil_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv_Perfil.RowCommand
        If e.CommandName = "editarPer" Then
            clearFieldDataPerfil()
            loadPerData(e.CommandArgument)
        ElseIf e.CommandName = "eliminaPer" Then
            eliminaPerfil(e.CommandArgument)
        End If
    End Sub

    Protected Sub eliminaPerfil(ByVal id As Integer)
        Dim array(), query2, resultTransaction As String
        Dim valor, q As String
        q = "select COUNT(*) as cantidad from TClientes where per_id = " & id
        valor = IDataBase.getSimpleData(q, "cantidad")
        If valor = "0" Then
            query2 = "delete from TPerfiles  where per_id = " & id
            IDataBase.addStringToArray(array, query2)
            resultTransaction = IDataBase.execute_commandsArray(array, lb_error)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('No puedes eliminar este perfil ya que al menos tiene un cliente asociado');", True)
        End If

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Perfil eliminado Exitosamente');", True)
        Else

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
        TabC1.ActiveTabIndex = 1
        'IControles.fillGridViewPaging(gv_Perfil, "select * from vwPerf where stat_id=1")
        IControles.fillGridViewPaging(gv_Perfil, "select * from vwPerf")
    End Sub

    Protected Sub btn_cancPer_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_cancPer.Click
        clearFieldDataPerfil()
    End Sub

#End Region

#Region "Emisoras"

    Protected Sub loadgridEmisiras()
        Dim q6 As String
        Dim dtEmi As New DataTable
        q6 = "select * from tEmisoras where stat_id =1"
        IDataBase.createDataTable(dtEmi, q6)
        If dtEmi.Rows.Count <= 0 Then
            Label14.Visible = True
            Label14.Text = "No hay Emisoras registradas hasta el momento"
        Else
            Label14.Visible = False
            IControles.fillGridViewPaging(gv_Emisoras, q6)
        End If
    End Sub
    Protected Sub btn_regEmi_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_regEmi.Click


        Dim q1, q2, q3, dmlEmi(), resultTransaction, valEmi As String
        q1 = "Select Count(*) As Emisoras  from temisoras where emi_nombre='" & txt_nomEmi.Text & "' and stat_id=1"
        valEmi = IDataBase.getSimpleData(q1, "Emisoras")

        If valEmi <= 0 Then

            q2 = "insert into temisoras(emi_nombre,stat_id,emi_serie,emi_costo,emi_titular) values ('" & txt_nomEmi.Text & "', 1 ,'" & txt_Serie.Text & "','" & txt_costo.Text & "','" & Session("ActiveUserlogin") & "')"
            IDataBase.addStringToArray(dmlEmi, q2)
            q3 = "insert into temisora_tipos(emi_id,tipo_id,stat_id,et_titular) values (ident_current('temisoras')," & ddl_tipo.SelectedValue & ", 1 ,'" & Session("ActiveUserlogin") & "')"
            IDataBase.addStringToArray(dmlEmi, q3)


            resultTransaction = IDataBase.execute_commandsArray(dmlEmi, [lb_error])
            If resultTransaction = "OK" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Emisora Registrada Exitosamente');", True)
            Else

                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
            End If

        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('La emisora ya existe');", True)
        End If
        TabC1.ActiveTabIndex = 2
        clearFieldDataEmisoras()
        busquedaEmi()
        loadgridEmisiras()
    End Sub

    Public Sub LoadTipos()
        Dim query As String
        query = "select tipo_id, tipo_nombre from ttipos where stat_id = 1"

        IControles.fill_dropDownListBaseQuery(ddl_tipo, "ttipos", "tipo_id", "tipo_nombre", query)

    End Sub

    Protected Sub btn_modEmi_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_modEmi.Click
        Dim dmlUpdateEmi() As String
        Dim UpdateEmi, q2 As String
        Dim resultTransaction As String

        UpdateEmi = "update temisoras set emi_nombre = '" & txt_nomEmi.Text & "', stat_id = 1, emi_serie = '" & txt_Serie.Text & "', emi_costo = '" & txt_Costo.Text & "', emi_titular = '" & Session("ActiveUserLogin") & "' where emi_id = " & Session("emi_id")

        IDataBase.addStringToArray(dmlUpdateEmi, UpdateEmi)

        q2 = "update temisora_tipos set tipo_id = " & ddl_tipo.SelectedValue & ", stat_id = 1  where emi_id = " & Session("emi_id")
        IDataBase.addStringToArray(dmlUpdateEmi, q2)

        resultTransaction = IDataBase.execute_commandsArray(dmlUpdateEmi, lb_error)

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Emisora Modificada Exitosamente');", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
        TabC1.ActiveTabIndex = 2
        clearFieldDataEmisoras()
        busquedaEmi()
        loadgridEmisiras()
    End Sub

    Protected Sub gv_Emisoras_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles gv_Emisoras.PageIndexChanging
        'Dim query As String = "select distinct(emi_nombre) from vwEmisoras"
        Dim query As String = "select * from vwEmisoras"
        'Dim query As String = "select emi_nombre, emi_serie, tipo_nombre, emi_costo from tEmisoras e, TTipos t, TEmisora_Tipos et where et.emi_id = e.emi_id and et.tipo_id = t.tipo_id "

        IControles.fillGridViewPaging(gv_Emisoras, query, e.NewPageIndex)
    End Sub

    Protected Sub gv_Emisoras_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv_Emisoras.RowCommand
        If e.CommandName = "editarEmi" Then
            clearFieldDataEmisoras()
            loadEmiData(e.CommandArgument)
        ElseIf e.CommandName = "eliminarEmi" Then
            eliminaEmisora(e.CommandArgument)
        End If
    End Sub

    Protected Sub loadEmiData(ByVal emi_ID As Integer)
        btn_regEmi.Visible = False
        btn_modEmi.Visible = True


        Dim dt As New DataTable
        Dim dt2 As New DataTable

        Dim datosEmi As String = "select * from tEmisoras where emi_id ='" & emi_ID & "'"
        'Dim datosEmi As String = "select emi_nombre, emi_serie, tipo_nombre, emi_costo from tEmisoras e, TTipos t, TEmisora_Tipos et where et.emi_id = e.emi_id and et.tipo_id = t.tipo_id and emi_id ='" & emi_ID & "'"
        'select emi_nombre, emi_serie, tipo_nombre, emi_costo from tEmisoras e, TTipos t, TEmisora_Tipos et where et.emi_id = e.emi_id and et.tipo_id = t.tipo_id  
        IDataBase.createDataTable(dt, datosEmi)

        If dt IsNot Nothing Then
            txt_nomEmi.Text = dt.Rows(0)("emi_nombre")
            txt_Serie.Text = dt.Rows(0)("emi_serie")
            'ddl_tipo.SelectedValue = dt.Rows(0)("tipo_nombre")
            txt_Costo.Text = Replace(dt.Rows(0)("emi_costo"), ",", ".")

            Dim query As String
            query = "select et_id, emi_id,tipo_id,stat_id from temisora_tipos where emi_id = " & emi_ID
            IDataBase.createDataTable(dt2, query)

            If dt2 IsNot Nothing Then
                ddl_tipo.SelectedValue = dt2.Rows(0)("tipo_id")
            End If


        End If
        Session("emi_id") = emi_ID

    End Sub

    Protected Sub clearFieldDataEmisoras()
        btn_regEmi.Visible = True
        btn_modEmi.Visible = False

        txt_nomEmi.Text = ""
        txt_Serie.Text = ""
        txt_Costo.Text = ""
        ddl_tipo.ClearSelection()
        'ddl_statusPer.SelectedValue = "None"

    End Sub

    Protected Sub eliminaEmisora(ByVal id As Integer)
        Dim array(), query2, query3, resultTransaction As String
        Dim valor, q As String
        q = "select SUM(Titulos) as cantidad from vwTitulosT where emi_id = " & id
        valor = IDataBase.getSimpleData(q, "cantidad")
        If valor <= "0" Then
            query2 = "Update TEmisoras SET stat_id = 2 where emi_id = " & id
            query3 = "update temisora_tipos set stat_id = 2 where emi_id = " & id
            IDataBase.addStringToArray(array, query2)
            IDataBase.addStringToArray(array, query3)
            resultTransaction = IDataBase.execute_commandsArray(array, lb_error)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('No puedes eliminar esta emisora ya que al menos tiene un movimiento asociado');", True)
        End If

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Emisora eliminada Exitosamente');", True)
        Else

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
        TabC1.ActiveTabIndex = 2
        IControles.fillGridViewPaging(gv_Emisoras, "select * from vwEmisoras where stat_id = 1")
        clearFieldDataEmisoras()
        busquedaEmi()
        loadgridEmisiras()
    End Sub

    Protected Sub btn_canEmi_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_canEmi.Click
        clearFieldDataEmisoras()
    End Sub

    Protected Sub busquedaEmi()
        Dim qr As String

        'qr = "select * from vwEmisoras where emi_nombre like '" & txtBusquedaEmisora.Text & "%'"
        qr = "select * from tEmisoras where emi_nombre like '" & txtBusquedaEmisora.Text & "%' and stat_id = 1"
        'qr = "select emi_nombre, emi_serie, tipo_nombre, emi_costo from tEmisoras e, TTipos t, TEmisora_Tipos et where et.emi_id = e.emi_id and et.tipo_id = t.tipo_id "
        IControles.fillGridViewPaging(gv_Emisoras, qr)
    End Sub
    Protected Sub lupa_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles lupa.Click
        busquedaEmi()
    End Sub


#End Region

#Region "Despachos"
    Protected Sub loadgridDespachos()
        Dim dtDesp As New DataTable
        Dim q7 As String

        q7 = "select * from vwDespachos"
        IDataBase.createDataTable(dtDesp, q7)

        If dtDesp.Rows.Count <= 0 Then
            Label15.Visible = True
            Label15.Text = "No hay despachos registrados hasta el momento"
        Else
            Label15.Visible = False
            IControles.fillGridViewPaging(gv_despachos, q7)
        End If
    End Sub

    Protected Sub registrarDespachos_Click(ByVal sender As Object, ByVal e As EventArgs) Handles registrarDespachos.Click
        Dim query, dmlDespachos(), resultTransaction As String

        Dim q1, valDesp As String
        q1 = "Select Count(*) As Despachos  from TDespachos where desp_nombre='" & txtNombreDesp.Text & "' and stat_id=1"
        valDesp = IDataBase.getSimpleData(q1, "Despachos")

        If valDesp <= 0 Then
            query = "INSERT INTO tDespachos (desp_nombre, desp_calle,desp_numero,desp_colonia, desp_CP,pais_nombre,mun_nombre, edo_nombre, desp_tel1, desp_tel2, desp_tel3, stat_id, desp_titular, desp_fecha_registro) " & _
                    "VALUES ('" & txtNombreDesp.Text & "', '" & txt_calle.Text & "', '" & txt_numeroDesp.Text & "', '" & txt_coloniaDesp.Text & "', '" & txt_cp1.Text & "', '" & txt_paisDesp.Text.ToUpper & "', '" & txt_munDesp.Text.ToUpper & "', '" & txt_edoDesp.Text.ToUpper & "', '" & txt_telefono1.Text & "', '" & txt_telefono2.Text & "', '" & txt_telefono3.Text & "', ' 1 ', '" & Session("ActiveUserLogin") & "', default)"
            IDataBase.addStringToArray(dmlDespachos, query)
            resultTransaction = IDataBase.execute_commandsArray(dmlDespachos, lb_error_d)
            If resultTransaction = "OK" Then
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Despacho Registrado Exitosamente');", True)
            Else
                ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
            End If
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('El despacho ya existe');", True)
        End If
        TabC1.ActiveTabIndex = 3
        'IControles.fillGridViewPaging(gv_Despacho, "select * from vwDespachos where stat_id=1")
        IControles.fillGridViewPaging(gv_despachos, "select * from vwDespachos")
        clearFieldDesp()
        loadgridDespachos()
    End Sub

    Protected Sub modificar_despacho_Click(ByVal sender As Object, ByVal e As EventArgs) Handles modificar_despacho.Click
        Dim resultTransaction, dmlUpdateDesp(), updateDesp As String

        updateDesp = "UPDATE tDespachos SET desp_nombre = '" & txtNombreDesp.Text & "', desp_calle = '" & txt_calle.Text & "', desp_numero = '" & txt_numeroDesp.Text & "', desp_colonia = '" & txt_coloniaDesp.Text & "', desp_CP = '" & txt_cp1.Text & "', pais_nombre = '" & txt_paisDesp.Text.ToUpper & "', mun_nombre = '" & txt_munDesp.Text.ToUpper & "', edo_nombre = '" & txt_edoDesp.Text & "', desp_tel1 = '" & txt_telefono1.Text & "', desp_tel2 = '" & txt_telefono2.Text & "', desp_tel3 = '" & txt_telefono3.Text & "', stat_id = 1 WHERE desp_id = " & Session("desp_id")
        IDataBase.addStringToArray(dmlUpdateDesp, updateDesp)

        resultTransaction = IDataBase.execute_commandsArray(dmlUpdateDesp, lb_error_d)

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Despacho Modificado Exitosamente');", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If

        TabC1.ActiveTabIndex = 3
        IControles.fillGridViewPaging(gv_despachos, "select * from vwDespachos")
        clearFieldDesp()
        loadgridDespachos()
    End Sub

    Protected Sub gv_despachos_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv_despachos.RowCommand
        If e.CommandName = "editarDesp" Then
            clearFieldDesp()
            loadDespData(e.CommandArgument)
        ElseIf e.CommandName = "eliminarDesp" Then
            eliminaDespacho(e.CommandArgument)
        End If
    End Sub

    Protected Sub eliminaDespacho(ByVal id As Integer)
        Dim array(), query2, resultTransaction As String
        Dim valor, q As String
        q = "select COUNT(*) as cantidad from TClientes where desp_id = " & id
        valor = IDataBase.getSimpleData(q, "cantidad")
        If valor = "0" Then
            query2 = "delete from TDespachos  where desp_id = " & id
            IDataBase.addStringToArray(array, query2)
            resultTransaction = IDataBase.execute_commandsArray(array, lb_error)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('No puedes eliminar este despacho ya que al menos tiene un cliente asociado');", True)
        End If

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Despacho eliminado Exitosamente');", True)
        Else

            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
        End If
        TabC1.ActiveTabIndex = 3
        'IControles.fillGridViewPaging(gv_Despacho, "select * from vwDespachos where stat_id=1")
        IControles.fillGridViewPaging(gv_despachos, "select * from vwDespachos")
        clearFieldDesp()
        loadgridDespachos()
    End Sub

    Sub loadDespData(ByVal desp_ID As Integer)
        registrarDespachos.Visible = False
        modificar_despacho.Visible = True

        Dim dt As New DataTable
        Dim datosdesp As String = "SELECT Distinct TOP 1 * FROM tDespachos WHERE desp_id = '" & desp_ID & "'"
        IDataBase.createDataTable(dt, datosdesp)

        If dt IsNot Nothing Then
            txtNombreDesp.Text = dt.Rows(0)("desp_nombre")
            txt_calle.Text = dt.Rows(0)("desp_calle")
            txt_numeroDesp.Text = dt.Rows(0)("desp_numero")
            txt_coloniaDesp.Text = dt.Rows(0)("desp_colonia")
            txt_cp1.Text = dt.Rows(0)("desp_CP")
            txt_paisDesp.Text = dt.Rows(0)("pais_nombre")
            txt_munDesp.Text = dt.Rows(0)("mun_nombre")
            txt_edoDesp.Text = dt.Rows(0)("edo_nombre")



            txt_telefono1.Text = dt.Rows(0)("desp_tel1")
            txt_telefono2.Text = dt.Rows(0)("desp_tel2")
            txt_telefono3.Text = dt.Rows(0)("desp_tel3")
            'ddl_estatus_desp.SelectedValue = dt.Rows(0)("stat_id")

        End If
        Session("desp_id") = desp_ID
    End Sub

    Sub clearFieldDesp()
        registrarDespachos.Visible = True
        modificar_despacho.Visible = False

        txtNombreDesp.Text = ""
        txt_calle.Text = ""
        txt_numeroDesp.Text = ""
        txt_coloniaDesp.Text = ""
        txt_cp1.Text = ""
        txt_paisDesp.Text = ""
        txt_munDesp.Text = ""
        txt_edoDesp.Text = ""
        txt_telefono1.Text = ""
        txt_telefono2.Text = ""
        txt_telefono3.Text = ""
        'ddl_estatus_desp.ClearSelection()

    End Sub

    Protected Sub btnCanDesp_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCanDesp.Click
        clearFieldDesp()
    End Sub

#End Region

#Region "IVA"
    Protected Sub btnIVA_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnIVA.Click
        Dim resultTransaction, dmlUpdateDesp(), updateDesp As String

        updateDesp = "UPDATE Tiva SET iva_valor = " & txtIVA.Text & " WHERE iva_id = 1"
        IDataBase.addStringToArray(dmlUpdateDesp, updateDesp)

        resultTransaction = IDataBase.execute_commandsArray(dmlUpdateDesp, lb_error_d)

        If resultTransaction = "OK" Then
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('IVA actualizado Exitosamente');", True)
        Else
            ScriptManager.RegisterStartupScript(Page, Me.GetType(), "PopupScript", "alert('Error En Transacción : " & Replace(resultTransaction, "'", "") & " \n\n Consulta Al Administrador Del Sistema');", True)
            Exit Sub
        End If
        TabC1.ActiveTabIndex = 4
        'IControles.fillGridViewPaging(gv_Despacho, "select * from vwDespachos where stat_id=1")
        'IControles.fillGridViewPaging(gv_despachos, "select * from vwDespachos")
        'clearFieldDesp()
    End Sub
#End Region

    Protected Sub gv_despachos_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewSelectEventArgs) Handles gv_despachos.SelectedIndexChanging
        IControles.fillGridViewPaging(gv_despachos, "select * from vwDespachos", e.NewSelectedIndex)
    End Sub

    Protected Sub gv_Emisoras_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gv_Emisoras.SelectedIndexChanged

    End Sub

    Protected Sub txt_Costo_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_Costo.TextChanged

    End Sub


    Protected Sub txt_telefono3_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_telefono3.TextChanged

    End Sub

    Protected Sub txt_coloniaDesp_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt_coloniaDesp.TextChanged

    End Sub
End Class
